﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-
# KonomeBot developed by Farseerfc,irolary
#if you would like to join in the develop, please twitter @irolar
#xmpp_handler, provide main founction

from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from db_model import KonoDB,DBservice
from kono_service import KonoService,Cmd_setup
from req_handler import KonoCmd, Cmd_c, Cmd_st, Cmd_hello,Cmd_h,Cmd_hi,Cmd_help, Cmd_version, Cmd_roe,Cmd_ml

class XMPPHandler(webapp.RequestHandler):
    def post(self):
        message = xmpp.Message(self.request.POST)
        address=message.sender.encode('utf8').split("/")[0].lower()
        konouser=KonoService()
        konouser.addUser(address)
        try :
            args = message.body.encode('utf8').strip().split(' ')
            for i in range(args.count('')):
                args.remove('')
            cmd_str = 'help'                         # default command is help
            cmd = Cmd_help(message,args)
            if len(args) >= 1:
                cmd_str = args[0].strip().lower()
            cmd_name = 'Cmd_'+cmd_str
            if cmd_name in  globals() :              # search for the Class with name Cmd_($command_name)
                if cmd_name !='setup':
                    cmd = eval (cmd_name + '(message,args)')
                else:
                    cmd = eval (cmd_name + '(message,args,add)')
            cmd.reply()                               # let it do the reply
        except Exception,e:
            message.reply( 'Error: %s !' % e )        # if error, send error message via xmpp
            raise

application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
